<template>
  <div class="goods-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>商品管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">添加商品</el-button>
      </div>

      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="goodsList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80">
        </el-table-column>
        <el-table-column prop="name" label="商品名称">
        </el-table-column>
        <el-table-column label="商品图片">
          <template slot-scope="scope">
            <el-image style="width: 80px; height: 80px" :src="scope.row.image" :preview-src-list="[scope.row.image]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类">
          <template slot-scope="scope">
            {{ scope.row.category | categoryFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格">
          <template slot-scope="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="总库存">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status | statusTextFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="goodsForm" :rules="rules" ref="goodsForm" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="goodsForm.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="goodsForm.category" placeholder="请选择商品分类">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="goodsForm.price" :min="0" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
        <el-form-item label="商品图片" prop="image">
          <!-- /api/upload -->
          <el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="goodsForm.image" :src="goodsForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="goodsForm.description" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="goodsForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsList, addGoods, updateGoods, deleteGoods } from '@/api/goods'

export default {
  name: 'Goods',
  filters: {
    categoryFilter (category) {
      const categoryMap = {
        'drink': '饮料',
        'snack': '零食',
        'daily': '日用品',
        'other': '其他'
      }
      return categoryMap[category] || '其他'
    },
    statusFilter (status) {
      return status === 1 ? 'success' : 'danger'
    },
    statusTextFilter (status) {
      return status === 1 ? '上架' : '下架'
    }
  },
  data () {
    return {
      queryParams: {
        name: '',
        category: '',
        pageNum: 1,
        pageSize: 10
      },
      categoryOptions: [
        { value: 'drink', label: '饮料' },
        { value: 'snack', label: '零食' },
        { value: 'daily', label: '日用品' },
        { value: 'other', label: '其他' }
      ],
      goodsList: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      dialogTitle: '',
      goodsForm: {
        id: '',
        name: '',
        category: '',
        price: 0,
        image: '',
        description: '',
        status: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.loading = true
      getGoodsList(this.queryParams).then(response => {
        this.goodsList = response.data.list
        this.total = response.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery () {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery () {
      this.queryParams = {
        name: '',
        category: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    handleSizeChange (val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.queryParams.pageNum = val
      this.getList()
    },
    handleAdd () {
      this.dialogTitle = '添加商品'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.goodsForm.resetFields()
        this.goodsForm = {
          id: '',
          name: '',
          category: '',
          price: 0,
          image: '',
          description: '',
          status: 1
        }
      })
    },
    handleEdit (index, row) {
      this.dialogTitle = '编辑商品'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.goodsForm = Object.assign({}, row)
      })
    },
    handleDelete (index, row) {
      this.$confirm('确认删除该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGoods(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitForm () {
      this.$refs.goodsForm.validate(valid => {
        if (valid) {
          const formData = { ...this.goodsForm };

          if (formData.id) {
            // 编辑
            updateGoods(formData).then(() => {
              this.dialogVisible = false;
              this.getList();
            });
          } else {
            // 添加
            addGoods(formData).then(() => {
              this.dialogVisible = false;
              this.getList();
            });
          }
        }
      });

      // this.$refs.goodsForm.validate(valid => {
      //   if (valid) {
      //     if (this.goodsForm.id) {
      //       updateGoods(this.goodsForm).then(response => {
      //         this.$message({
      //           type: 'success',
      //           message: '修改成功!'
      //         })
      //         this.dialogVisible = false
      //         this.getList()
      //       })
      //     } else {
      //       addGoods(this.goodsForm).then(response => {
      //         this.$message({
      //           type: 'success',
      //           message: '添加成功!'
      //         })
      //         this.dialogVisible = false
      //         this.getList()
      //       })
      //     }
      //   } else {
      //     return false
      //   }
      // })
    },
    handleImageSuccess (res, file) {
      this.goodsForm.image = URL.createObjectURL(file.raw)
      // 实际项目中这里应该上传到服务器并返回图片URL
      // this.goodsForm.image = res.data.url
    },
    beforeImageUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }

      this.goodsForm.image = URL.createObjectURL(file)
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-container {
  padding: 20px;

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .avatar-uploader {
    v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409EFF;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
</style>